package com.sotb.receiver;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.Projection;
/**
 * @author zsr
 * 在地图中显示history记录的位置
 */
public class HistoryMapActivity extends MapActivity{

	private MapView mapView;
	private MapController mapController;
	private List<Overlay> mapOverlays;
	private Projection projection;
	private String number;
	private String[][] location;
	private HistoryDbUtil historyDbUtil;
	private DatabaseHelper dbHelper;
	private SQLiteDatabase db;
	
    private int count = 0;
    private long firstClick = 0;
    private long secondClick = 0;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.map);
        
        mapView = (MapView)findViewById(R.id.map);
        mapView.setBuiltInZoomControls(true);	//设置用于缩放地图的工具条
        mapView.setSatellite(true); 	//设置为卫星地图（没有偏置）
        mapController = mapView.getController();
        mapOverlays = mapView.getOverlays();
        projection = mapView.getProjection();
        
        //从intent中抽取号码和位置信息
        Intent intent = this.getIntent();
        number = intent.getStringExtra("number");
        setTitle(number + "的历史记录");
        String locations = intent.getStringExtra("location");
        String[] spliteTemp = locations.split(" ");
        location = new String[spliteTemp.length][];
        for(int i = 0; i < spliteTemp.length; i++){
        	location[i] = spliteTemp[i].split(",");
        }
        
        markTrack(location, mapOverlays);
        
	}
	
	/**
	 * 标记路径
	 * @param s	经纬度坐标数组
	 * @param mapOverlays	地图层容器
	 */
	private void markTrack(String[][] s, List<Overlay> mapOverlays){
		if(s == null)System.out.println("location string is null");
		List<GeoPoint> geoPoints = new ArrayList<GeoPoint>();
		mapController.setZoom(16);
		//将String[][]中的位置信息转换成geopoint
		for(int i = 0; i < s.length; i++){
			GeoPoint geoPoint = new GeoPoint((int)(Double.parseDouble(s[i][1])*Math.pow(10, 6)), 
					(int)(Double.parseDouble(s[i][0])*Math.pow(10, 6)));
			geoPoints.add(geoPoint);
		}
		
		//不止一个点时绘制轨迹
		if(geoPoints.size() != 1){
			for(int i = 0; i < geoPoints.size() - 1; i++){
				LineOverlay lineOverlay = new LineOverlay(geoPoints.get(i), geoPoints.get(i + 1));
				mapOverlays.add(lineOverlay);
			}
			
		}
		
		//绘制终点
		GeoPoint endGeoPoint = geoPoints.get(geoPoints.size() - 1);
		PointOverlay endPointOverlay = new PointOverlay(endGeoPoint);
		mapOverlays.add(endPointOverlay);
		mapController.animateTo(endGeoPoint);
	}
	
	/**该类的对象用于在地图上绘制线条*/
	class LineOverlay extends Overlay {
		private GeoPoint begin;
		private GeoPoint end;

		public LineOverlay(GeoPoint begin, GeoPoint end) {
			this.begin = begin;
			this.end = end;
		}

		public void draw(Canvas canvas, MapView mapv, boolean shadow) {
			super.draw(canvas, mapv, shadow);
			Paint paint = new Paint();
			paint.setColor(Color.BLUE);
			paint.setStyle(Paint.Style.FILL_AND_STROKE);
			paint.setStrokeWidth(4);
			Point beginPoint = new Point();
			Point endPoint = new Point();
			Path path = new Path();
			projection.toPixels(begin, beginPoint);
			projection.toPixels(end, endPoint);
			path.moveTo(endPoint.x, endPoint.y);
			path.lineTo(beginPoint.x, beginPoint.y);
			canvas.drawPath(path, paint);
		}
	}
		
	/**该类的对象的作用是在地图上绘制图标*/
	class PointOverlay extends Overlay {
		private GeoPoint geoPoint;
		
		public PointOverlay(GeoPoint geoPoint) {
			this.geoPoint = geoPoint;
		}

		public void draw(Canvas canvas, MapView mapv, boolean shadow) {
			super.draw(canvas, mapv, shadow);
			Point point = new Point();
			projection.toPixels(geoPoint, point);
			Bitmap bmp = BitmapFactory.decodeResource(getResources(),R.drawable.red_dot);
			Paint paint = new Paint();
			canvas.drawBitmap(bmp, point.x - bmp.getWidth()/2, point.y - bmp.getHeight(), paint);
		}
	}
	
	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}
	
	/**创建menu*/
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, Constant.COMPLETE, 0, "接警完成");
		return true;
	}

	/**响应点击menu事件*/
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()){
		case Constant.COMPLETE:{
			Thread thread = new Thread(new WriteCompleteToDB(number));
			thread.start();
		}break;
		}
		return true;
	}
	
	/**把接警完成的状态写入数据库*/
	class WriteCompleteToDB implements Runnable{
		private String s;
		WriteCompleteToDB(String s){
			this.s = s;
		}
		public void run() {
			//实例化数据库管理工具
	        dbHelper = new DatabaseHelper(HistoryMapActivity.this,"receiver_db", Constant.DB_VERSION);
			db = dbHelper.getWritableDatabase();
	        historyDbUtil = new HistoryDbUtil(db);
			historyDbUtil.updateReceiveComplete(s);
			db.close();
		}			
	}
	
	/**响应双击地图事件*/
	@Override  
    public boolean dispatchTouchEvent(MotionEvent ev) {  
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {  
            count++;  
            if(count==1){  
                firstClick = System.currentTimeMillis();  
            }else if(count==2){  
                secondClick = System.currentTimeMillis();  
                if (secondClick - firstClick < 500) {  
                    mapView.getController().zoomInFixing((int) ev.getX(),  
                            (int) ev.getY());  
                }  
                count = 0;  
                firstClick = 0;  
                secondClick = 0;  
            }  
        }  
        return super.dispatchTouchEvent(ev);  
    }  
}
